package com.iflytek.esb.function;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.iflytek.esb.domain.Message;
import com.iflytek.esb.exceptions.RetryableException;
import com.iflytek.esb.util.WebRequest;
import com.opensymphony.module.propertyset.PropertySet;
import com.opensymphony.workflow.WorkflowException;

public class WebServiceSender extends MessageFunction {

	private static final Logger LOG = Logger.getLogger(WebServiceReceiver.class);
	
	private static final String ONE_WAY = "one-way";
	private static final String REQUEST_RESPONSE = "request-response";
	
	private static WebRequest webRequest;
	
	public WebServiceSender() {
		if (webRequest == null) {
			webRequest = new WebRequest();
		}
	}
	
	protected void process(Message message, 
			final Map<String, String> args,
			PropertySet ps) throws WorkflowException, RetryableException {
		
		LOG.debug("<invoke web service send>");
		
		String intervalS = args.get("interval.seconds");
		String maxtryS = args.get("max.try");
		String uri = args.get("uri");
		String type = args.get("type");
		
		int interval = 0;
		int maxtry = 0;
		try {
			try {
				interval = Integer.parseInt(intervalS);
			}
			catch (NumberFormatException e) {
			}
			
			try {
				maxtry = Integer.parseInt(maxtryS);
			}
			catch (NumberFormatException e) {
			}
			
			//String soap = SoapUtil.getEnvelope(message.getBody());
			LOG.debug("send message out, and wait response, headers: " + message.getHeaders());
			Message tm = webRequest.post(uri, message.getContent(), message.getHeaders());
			
			//String body = SoapUtil.getBody(tm.getBody());
			LOG.debug("get message return back, headers: " + tm.getHeaders());
			
			if (StringUtils.equals(type, ONE_WAY)) {
				//do nothing
			}
			else if (StringUtils.equals(type, REQUEST_RESPONSE)) {
				message.setContent(tm.getContent());
				message.setHeaders(tm.getHeaders());
			}
		} 
		catch (MalformedURLException e) {
			throw new WorkflowException(e);
		}
		catch (IOException e) {
			throw new RetryableException(interval, maxtry, e);
		}
	}

}
